package com.yykj.prescription.server.service.impl;

import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.message.center.client.dto.DrugOrderMessageBodyDTO;
import com.yykj.message.center.client.feign.MessageFeignClient;
import com.yykj.prescription.server.model.entity.prescription.DoctorPrescriptionStatistic;
import com.yykj.prescription.server.model.entity.prescription.HospitalPrescriptionStatistic;
import com.yykj.prescription.server.model.entity.prescription.Prescription;
import com.yykj.prescription.server.model.repository.prescription.DoctorPrescriptionStatisticRepository;
import com.yykj.prescription.server.model.repository.prescription.HospitalPrescriptionStatisticRepository;
import com.yykj.prescription.server.model.repository.prescription.PrescriptionRepository;
import com.yykj.prescription.server.service.StatisticService;
import com.yykj.user.center.client.dto.PatientInfoDto;
import com.yykj.user.center.client.feign.UserFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.time.LocalDate;

@Service
@Transactional
@Slf4j
public class StatisticServiceImpl implements StatisticService {
    @Override
    public void prescriptionOrderCreated(Integer hospitalId, String prescriptionId) {
        //根据处方下单了，开始处理
        Prescription prescription = prescriptionRepository.findById(prescriptionId).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
        if (prescription.getHospitalId() == null || !prescription.getHospitalId().equals(hospitalId)) {
            throw new NormalException(ResultEnums.PARAM_ERROR);
        }
        if (Boolean.FALSE.equals(prescription.getEndless())) {//剩余次数减一
            prescription.setCnt(prescription.getCnt() - 1);
            prescriptionRepository.save(prescription);
        }
        increaseHospitalUse(prescription.getHospitalId(),prescription.getAddTime().toLocalDate());
        increaseDoctorUse(prescription.getHospitalId(),prescription.getDoctorId(),prescription.getAddTime().toLocalDate());
    }

    @Override
    public void prescriptionCreated(Integer hospitalId, String prescriptionId) {
        Prescription prescription = prescriptionRepository.findById(prescriptionId).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
        if (prescription.getHospitalId() == null || !prescription.getHospitalId().equals(hospitalId)) {
            throw new NormalException(ResultEnums.PARAM_ERROR);
        }
        increaseHospitalCreated(hospitalId,prescription.getAddTime().toLocalDate());
        increaseDoctorCreated(prescription.getHospitalId(),prescription.getDoctorId(),prescription.getAddTime().toLocalDate());

        try {
            log.info("处方新建成功：尝试发送短信给患者：");
            if(StringUtils.hasText(prescription.getUserId())){
                PatientInfoDto patientInfoDto = userFeignClient.patientInfo(prescription.getUserId());
                if(patientInfoDto!=null){
                    if(StringUtils.hasText(patientInfoDto.getMobile())){
                        log.info("发送短信：mobile = {},doctorName = {}",patientInfoDto.getMobile(),prescription.getDoctorName());
                        messageFeignClient.smsPatientPrescriptionSuccess(patientInfoDto.getMobile(), prescription.getDoctorName());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void increaseDoctorCreated(Integer hospitalId,String doctorId, LocalDate day) {
        log.info("增加医生处方创建数量doctorId = {},day = {}",doctorId,day);
        increaseDoctor(hospitalId,doctorId,day,1,0);
    }

    private void increaseDoctorUse(Integer hospitalId,String doctorId, LocalDate day) {
        log.info("增加医生处方使用数量doctorId = {},day = {}",doctorId,day);
        increaseDoctor(hospitalId,doctorId,day,0,1);
    }

    private void increaseDoctor(Integer hospitalId,String doctorId, LocalDate day,Integer createCnt ,Integer useCnt) {
        DoctorPrescriptionStatistic doctorStatistic = doctorStatisticRepository.findByHospitalIdAndDoctorIdAndDay(hospitalId, doctorId,day);
        if (doctorStatistic == null) {
            doctorStatistic = new DoctorPrescriptionStatistic();
            doctorStatistic.setHospitalId(hospitalId);
            doctorStatistic.setDoctorId(doctorId);
            doctorStatistic.setDay(day);
        }
        doctorStatistic.setCnt(doctorStatistic.getCnt()+createCnt);
        doctorStatistic.setUseCnt(doctorStatistic.getUseCnt()+useCnt);
        doctorStatisticRepository.save(doctorStatistic);
    }


    private void increaseHospitalCreated(Integer hospitalId, LocalDate day) {
        log.info("增加医院处方创建数量 hospitalId = {},day = {}",hospitalId,day);
         increaseHospital(hospitalId,day,1,0);
    }

    private void increaseHospitalUse(Integer hospitalId, LocalDate day) {
        log.info("增加医院处方使用数量 hospitalId = {},day = {}",hospitalId,day);
         increaseHospital(hospitalId,day,0,1);
    }

    private void increaseHospital(Integer hospitalId, LocalDate day,Integer createCnt ,Integer useCnt) {

        HospitalPrescriptionStatistic hospitalStatistic = hospitalStatisticRepository.findByHospitalIdAndDay(hospitalId, day);
        if (hospitalStatistic == null) {
            hospitalStatistic = new HospitalPrescriptionStatistic();
            hospitalStatistic.setHospitalId(hospitalId);
            hospitalStatistic.setDay(day);
        }
        hospitalStatistic.setCnt(hospitalStatistic.getCnt()+createCnt);
        hospitalStatistic.setUseCnt(hospitalStatistic.getUseCnt() + useCnt);
        hospitalStatisticRepository.save(hospitalStatistic);
    }

    private DoctorPrescriptionStatisticRepository doctorStatisticRepository;

    private HospitalPrescriptionStatisticRepository hospitalStatisticRepository;

    private PrescriptionRepository prescriptionRepository;

    private UserFeignClient userFeignClient;

    private MessageFeignClient messageFeignClient;

    @Autowired
    public void setPrescriptionRepository(PrescriptionRepository prescriptionRepository) {
        this.prescriptionRepository = prescriptionRepository;
    }

    @Autowired
    public void setHospitalStatisticRepository(HospitalPrescriptionStatisticRepository hospitalStatisticRepository) {
        this.hospitalStatisticRepository = hospitalStatisticRepository;
    }
    @Autowired
    public void setDoctorStatisticRepository(DoctorPrescriptionStatisticRepository doctorStatisticRepository) {
        this.doctorStatisticRepository = doctorStatisticRepository;
    }

    @Autowired
    public void setUserFeignClient(UserFeignClient userFeignClient) {
        this.userFeignClient = userFeignClient;
    }

    @Autowired
    public void setMessageFeignClient(MessageFeignClient messageFeignClient) {
        this.messageFeignClient = messageFeignClient;
    }
}
